import { prisma } from '@/lib/prisma/client'
import { NextResponse } from 'next/server'

export async function PUT(
  request: Request,
  { params }: { params: { id: string } }
) {
  try {
    const { id } = await Promise.resolve(params)
    const data = await request.json()

    // 构建更新数据对象
    const updateData: any = {}
    
    // 如果有状态更新
    if (data.status !== undefined) {
      updateData.status = data.status
    }

    // 如果有设备数据更新，作为字符串存储
    if (data.data !== undefined) {
      updateData.data = JSON.stringify(data.data)
    }

    const device = await prisma.device.update({
      where: { id },
      data: updateData
    })

    return NextResponse.json(device)
  } catch (error) {
    console.error('更新设备失败:', error)
    return NextResponse.json(
      { error: '更新设备失败' },
      { status: 500 }
    )
  }
}

export async function GET(
  request: Request,
  { params }: { params: { id: string } }
) {
  try {
    const { id } = await Promise.resolve(params)
    const device = await prisma.device.findUnique({
      where: { id }
    })

    if (!device) {
      return NextResponse.json(
        { error: '设备不存在' },
        { status: 404 }
      )
    }

    // 解析设备数据
    return NextResponse.json({
      ...device,
      data: device.data ? JSON.parse(device.data) : null
    })
  } catch (error) {
    return NextResponse.json(
      { error: '获取设备失败' },
      { status: 500 }
    )
  }
}

export async function DELETE(
  request: Request,
  { params }: { params: { id: string } }
) {
  try {
    const { id } = await Promise.resolve(params)
    await prisma.device.delete({
      where: { id }
    })

    return NextResponse.json({ success: true })
  } catch (error) {
    return NextResponse.json(
      { error: '删除设备失败' },
      { status: 500 }
    )
  }
} 